package com.sz.common.base.utils;

import java.net.InetAddress;
import java.util.Random;
import java.util.UUID;

/**
 * Function: TODO: ADD FUNCTION <br>
 * Author: Charles. <br>
 * Date: 2017-02-24 14:09:00.
 */
public class UUIDGenerator {

    /**
     * @return
     */
    public static String generateRandomUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }


    private static SnowflakeIdWorker worker = null;

    private static SnowflakeIdWorker getSnowflakeIdWorker() {
        if (worker == null) {
            //serverId和workerId的范围 [0,32)
            int serverId = getServerId();
            int workerId = new Random().nextInt(32);
            worker = new SnowflakeIdWorker(workerId, serverId);
        }
        return worker;
    }

    private static int getServerId() {
        try {
            //服务器集群中IP地址一般是连续的，所以取IP地址最后5位，基本可以保证serverId不会重复
            byte[] bytes = InetAddress.getLocalHost().getAddress();
            byte byta = bytes[3];
            int num = ((byta & 0x1F) & 0xFF); //取IP地址的最后5位bit
            return num;
        } catch (Exception ex) {
            //获取不到IP，取随机码
            return new Random().nextInt(32);
        }
    }


    public static String generateOrderedUUID() {
        return String.valueOf(getSnowflakeIdWorker().nextId());
    }
}
